<script lang="jsx" setup>
import { nextTick, ref } from 'vue';
import { useElementSize } from '@vueuse/core';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons-vue';
import useResetTableRef from '@/hooks/common/resetTableRef';
import useSearchData from '@/hooks/common/searchData';
import {
  addVentBoard,
  auditVentBoard,
  deleteVentBoard,
  editVentBoard,
  scrapVentBoard
} from '@/service/api/modules/workwear/vent-board';

// import Charts from './modules/charts.vue';

import Add from './modules/add.vue';

const useModal = window.$useModal;
const [searchParams, resetSearchParams] = useResetTableRef({
  model: null,
  states: null,
  time: null
});

const searchRef = ref(null);
const { height } = useElementSize(searchRef);
console.log('height', height);

const searchFormList = [
  {
    type: 'input',
    key: 'model',
    label: '型号',
    placeholder: '请输入型号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },
  {
    type: 'select',
    key: 'states',
    label: '状态',
    placeholder: '请输入状态',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6,
    selectOptions: [
      { label: '未审核', value: 0 },
      { label: '生效', value: 1 },
      { label: '已报废', value: 2 }
    ]
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '日期',
    span: 24,
    md: 12,
    lg: 10,
    xl: 8,
    xxl: 6,
    showTime: true
  }
];

const tableRef = ref(null);
const searchData = useSearchData(searchParams);

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'model',
    dataIndex: 'model',
    title: '型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 170
  },
  {
    key: 'states',
    dataIndex: 'states',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      const obj = {
        0: {
          text: '未审核',
          color: 'orange'
        },
        1: {
          text: '生效',
          color: 'green'
        },
        2: {
          text: '已报废',
          color: 'red'
        }
      };

      return <a-tag color={obj[record.states].color}>{obj[record.states].text}</a-tag>;
    }
  },
  {
    key: 'position',
    dataIndex: 'position',
    title: '存放位置',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'category',
    dataIndex: 'category',
    title: '类别',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'printCount',
    dataIndex: 'printCount',
    title: '导气板数量',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'applicant',
    dataIndex: 'applicant',
    title: '申请人',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'applicationtime',
    dataIndex: 'applicationtime',
    title: '申请时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 170
  },
  {
    key: 'scrapper',
    dataIndex: 'scrapper',
    title: '报废人',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'scraptime',
    dataIndex: 'scraptime',
    title: '报废时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 170
  },
  {
    key: 'reasonforscrapping',
    dataIndex: 'reasonforscrapping',
    title: '报废原因',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 170
  },
  {
    key: 'checker',
    dataIndex: 'checker',
    title: '审核人',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'checkTime',
    dataIndex: 'checkTime',
    title: '审核时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 170
  }
];

const tabaleSelect = ref([]);
function tableSelectChange(val) {
  tabaleSelect.value = val;
}

const currentRow = ref(null);
const addRef = ref(null);
const operationType = ref('add');
const { handleClose, handleLoading, handleShow, updateModalOptions } = useModal({
  modalOption: {
    width: '600px',
    destroyOnClose: true,
    title: '导气板新增'
  },
  component: () => <Add ref={addRef} rowData={currentRow.value}></Add>,
  onOk: async () => {
    const data = { ...addRef.value };
    await data.validateForm();
    handleLoading(true);
    try {
      const formData = { ...data.model };
      let pro;
      if (operationType.value === 'add') {
        pro = await addVentBoard(formData);
      } else {
        pro = await editVentBoard({ ...formData });
      }
      const { error } = await pro;
      if (!error) {
        window.$message.success('操作成功');
        handleClose();
        search();
      }
    } finally {
      handleLoading(false);
    }
  }
});

function handleAdd(row) {
  currentRow.value = row;
  console.log('row', row);

  if (row) {
    operationType.value = 'edit';
    updateModalOptions({
      title: '导气板修改'
    });
  } else {
    operationType.value = 'add';
    updateModalOptions({
      title: '导气板新增'
    });
  }
  handleShow();
}

// 删除
const delLoading = ref(false);
const delConfirmObj = {
  title: '是否删除所勾选数据?',
  onOk: () => {
    delLoading.value = true;
    deleteVentBoard(tabaleSelect.value)
      .then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功!');
          search();
        }
      })
      .finally(() => {
        delLoading.value = false;
      });
  }
};

// 审核
const examineLoading = ref(false);
const examineConfirmObj = {
  title: '是否审核所勾选数据?',
  onOk: () => {
    examineLoading.value = true;
    auditVentBoard(tabaleSelect.value)
      .then(({ error }) => {
        if (!error) {
          window.$message.success('审核成功!');
          search();
        }
      })
      .finally(() => {
        examineLoading.value = false;
      });
  }
};

// 报废
const currentScrapRow = ref(null);
const {
  handleClose: handleScrapClose,
  handleLoading: handleScrapLoading,
  handleShow: handleScrapShow
} = useModal({
  modalOption: {
    title: '报废导气板',
    width: '600px',
    height: '300px',
    destroyOnClose: true
  },
  formData: {
    scrapReason: null
  },
  formList: [
    {
      type: 'textarea',
      key: 'reasonforscrapping',
      label: '报废原因',
      textareaRows: 3,
      placeholder: '请选择报废原因',
      span: 24
    }
  ],
  onOk: data => {
    handleScrapLoading(true);
    scrapVentBoard({
      ...data,
      id: currentScrapRow.value.id,
      states: currentScrapRow.value.states
    })
      .then(({ error }) => {
        if (!error) {
          window.$message.success('报废成功');
          currentScrapRow.value = null;
          handleScrapClose();
          search();
        }
      })
      .finally(() => {
        handleScrapLoading(false);
      });
  },
  onCancel: () => {}
});

function handleScrap(row) {
  if (Number(row.states) === 2) {
    window.$message.error('该导气板已报废，请勿重复操作!');
    return;
  }
  handleScrapShow();
  currentScrapRow.value = row;
}

function search() {
  tableRef.value.getData(1);
}

function reset() {
  resetSearchParams();
  nextTick(() => {
    search();
  });
}
</script>

<template>
  <div class="vent-board min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="searchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      ref="tableRef"
      v-model:searchParams="searchData"
      :column="column"
      show-row-selection
      class="h-full"
      :scroll="{ y: 'auto' }"
      is-init-get-data
      :auto-generate-uuid="true"
      :table-custom-row="tableCustomRow"
      url="/qms/ventBoard/list"
      :row-height="30"
      @table-select-change="tableSelectChange"
    >
      <template #title>
        <AButton
          v-hasAuth="['workwear:vent-board:add']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          @click="handleAdd(null)"
        >
          <template #icon>
            <PlusOutlined class="align-sub" />
          </template>
          新增
        </AButton>
        <AButton
          v-hasAuth="['workwear:vent-board:update']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="tabaleSelect.length != 1"
          @click="handleAdd(tabaleSelect[0])"
        >
          <template #icon>
            <EditOutlined class="align-sub" />
          </template>
          修改
        </AButton>

        <AButton
          v-hasAuth="['workwear:vent-board:delete']"
          v-confirm="delConfirmObj"
          :loading="delLoading"
          type="primary"
          danger
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="!tabaleSelect.length"
        >
          <template #icon>
            <DeleteOutlined class="align-sub" />
          </template>
          删除
        </AButton>

        <AButton
          v-hasAuth="['workwear:vent-board:scrap']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="tabaleSelect.length != 1"
          @click="handleScrap(tabaleSelect[0])"
        >
          <template #icon>
            <em class="iconfont icon-baofei align-sub"></em>
          </template>
          报废
        </AButton>

        <AButton
          v-hasAuth="['workwear:vent-board:examine']"
          v-confirm="examineConfirmObj"
          :loading="examineLoading"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="!tabaleSelect.length"
        >
          <template #icon>
            <em class="iconfont icon-shenhe align-sub"></em>
          </template>
          审核
        </AButton>
      </template>
    </Table>
  </div>
</template>

<style lang="scss" scoped>
// .chart {
//   :deep(.ant-card) {
//     .ant-card-body {
//       height: calc(100%);
//       .ant-spin-nested-loading,
//       .ant-spin-container {
//         height: 100%;
//       }
//     }
//   }
// }
</style>
